package com.apps.sdses.flink141.udfs;

import com.alibaba.fastjson2.JSON;
import org.apache.flink.table.functions.ScalarFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.Map;

/**
 * author: codejiwei
 * date: 2023/6/7
 * desc: parsing json factory
 **/
public class JsonExtractFunction extends ScalarFunction {

    private final Logger logger = LoggerFactory.getLogger(JsonExtractFunction.class);

    public String eval(String json, String path) {
        try {
            logger.info("eval json: " + json + " path: " + path + " thread: " + Thread.currentThread().getId());
            Map map = JSON.parseObject(json, Map.class);
            String[] keys = path.split("\\.");
            return getValue(Arrays.copyOfRange(keys, 1, keys.length), map);
        } catch (Exception e) {
            logger.warn("JsonExtract exception:" + e.getMessage() + " json:" + json + " path:" + path);
            return null;
        }

    }

    private String getValue(String[] keys, Map<String, Object> value) {
        if (keys.length > 0) {
            Object head = value.get(keys[0]);
            if (head instanceof Map) {
                return getValue(Arrays.copyOfRange(keys, 1, keys.length), (Map<String, Object>) head);
            } else if (keys.length == 1) {
                return head.toString();
            } else {
                throw new UnsupportedOperationException(String.join(".", Arrays.copyOfRange(keys, 1, keys.length)) + "." + head);
            }
        } else {
            return value.toString();
        }

    }

}
